package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.CartItem;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private Cart cart;
    @Autowired
    private CatalogService catalogService;
    @Autowired
    private HttpSession session;
    @Autowired
    private Account account;
    @Autowired
    private CartItem cartItem;


    //改持久化
    @GetMapping("/addItemToCart")
    public String addItemToCart(String workingItemId,Model model,HttpServletResponse response) throws IOException {
        PrintWriter out = null;
        response.setContentType("text/html; charset=UTF-8"); //转码
        int flag = 0;
        //若用户已登录，在登陆时flag被赋值为1
        if(session.getAttribute("flag")!=null)
        {
            flag = 1;

        }

            cart = (Cart) session.getAttribute("cart");
            if(cart==null) {
                cart = new Cart();
            }
        //当未登录时
        if(flag==0) {
            model.addAttribute("account",account);
            return "account/SignonForm";
        }
        else
        {
            account = (Account) session.getAttribute("account");
            if (cart.containsItemId(workingItemId)) {
                int quantity = catalogService.getQuantityByItemAndUserId(account.getUsername(),workingItemId);
                quantity++;
                BigDecimal price = catalogService.getListPriceByItemAndUserId(account.getUsername(),workingItemId);
                BigDecimal num;
                num = new BigDecimal(quantity);
                price = price.multiply(num);
                catalogService.incrementQuantityByItemId(quantity,price,account.getUsername(),workingItemId);
            } else {
                // isInStock is a "real-time" property that must be updated
                // every time an item is added to the cart, even if other
                // item details are cached.
                boolean isInStock = catalogService.isItemInStock(workingItemId);
                System.out.println(isInStock);
                if(isInStock) {
                    Item item = catalogService.getItem(workingItemId);
                    cart.addItem(item, isInStock);
                    //数据库中添加商品
                    catalogService.insertAccount(account.getUsername(), item);
                }
                else
                {
                    out = response.getWriter();
                    out.println("<script>");
                    out.println("alert('对不起，该商品暂时缺货！');");
                    out.println("history.back();");
                    out.println("</script>");
                    out.close();
                }
            }
            session.setAttribute("cart",cart);
            Iterator<CartItem> cartItem = cart.getAllCartItems();
            model.addAttribute("cartItem",cartItem);
            return "cart/cart";
        }


    }

    //改持久化
    @GetMapping("/removeItemFromCart")
    public String removeItemFromCart(String workingItemId,Model model) {

        account = (Account) session.getAttribute("account");
        Item item = cart.removeItemById(workingItemId);
        catalogService.deleteCartItemByUsernameAndItemid(account.getUsername(),workingItemId);

        if (item == null) {
//            setMessage("Attempted to remove null CartItem from Cart.");
//            return new ForwardResolution(ERROR);
            return "catalog/main";
        } else {
            model.addAttribute("cart",cart);
            Iterator<CartItem> cartItem = cart.getAllCartItems();
            model.addAttribute("cartItem",cartItem);
            return "cart/cart";
        }

    }

    //改持久化
    @GetMapping("/updateCartQuantities")
    public String updateCartQuantities(int quantity,String itemId,Model model,Cart cart) {

        Iterator<CartItem> cartItems = cart.getAllCartItems();
        while (cartItems.hasNext()) {
            CartItem cartItem = (CartItem) cartItems.next();
            try {
                if(itemId.equals(cartItem.getItem().getItemId())){
                    cart.setQuantityByItemId(itemId, quantity);
                }
                if (quantity < 1) {
                    cartItems.remove();
                }
            } catch (Exception e) {
                //ignore parse exceptions on purpose
            }
        }
        model.addAttribute("cart",cart);
        Iterator<CartItem> cartItem = cart.getAllCartItems();
        model.addAttribute("cartItem",cartItem);
        return "cart/cart";
    }

    @GetMapping("/updateCartItemQuantityAjax")
    @ResponseBody
    public double updateCartItemQuantityAjax(HttpServletResponse response,String itemId, String quantity, String username, Model model) throws IOException {
        int Quantity = Integer.parseInt(quantity);
        cart = (Cart) session.getAttribute("cart");
        Iterator<CartItem> cartItems = cart.getAllCartItems();
        Item item = catalogService.getItem(itemId);
        cartItem.setItem(item);
        cartItem.setInStock(Boolean.parseBoolean("true"));
        cartItem.setQuantity(Integer.parseInt(quantity));
        cart.setQuantityByItemId(itemId,Quantity);
        model.addAttribute("cart",cart);
        double sub = cart.getSubTotal().doubleValue();
        catalogService.updateCartItemQuantityAjax(username,itemId,Quantity);
        return sub;

//        cart.addItem(item,true);
//
//
//        session.setAttribute("cart", cart);
//
//        model.addAttribute("cart",cart);
////        catalogService.updateCartItemQuantityAjax(username,itemId,Quantity);
//        BigDecimal price = catalogService.getListPriceByItemAndUserId(username,itemId);
//        BigDecimal num;
//        num = new BigDecimal(Integer.parseInt(quantity));
//        price = price.multiply(num);
//        catalogService.incrementQuantityByItemId(Integer.parseInt(quantity),price,username,itemId);

//        return "cart/cart";
    }
    //改持久化
//    @GetMapping("/viewCart")
//    public String viewCart(Model model) {
//        session.setAttribute("cart",cart);
//        model.addAttribute("cart",cart);
////        Iterator<CartItem> cartItem = cart.getAllCartItems();
////        model.addAttribute("cartItem",cartItem);
//        return "cart/cart";
//    }

    //改路径
    @GetMapping("/checkOut")
    public String checkOut() {
        return "cart/cart";
    }

    @GetMapping("/clear")
    public void clear(String workingItemId, Model model,Cart cart) {
        workingItemId = null;
        model.addAttribute("cart",cart);
        Iterator<CartItem> cartItem = cart.getAllCartItems();
        model.addAttribute("cartItem",cartItem);
    }

    @GetMapping("/viewCart")
    //尝试使用model的getAttribute
    public String viewCategory(Model model)
    {
        cart = (Cart)session.getAttribute("cart");
        if(cart==null)
        {
            cart = new Cart();
            session.setAttribute("cart",cart);
            model.addAttribute("cart",cart);
        }

//        model.addAttribute("loginAccount",account);

        return "cart/Cart";

    }
    }



